<template>
    <view class="container p-bottom" v-if="goodsList.length && formData.length">
        <view class="goods-list">
            <view class="goods-item" v-for="(item, index) in goodsList" :key="index">
                <!-- 商品详情 -->

                <view class="goods-detail dis-flex flex-dir-row">
                    <view class="left">
                        <image class="goods-image" :src="item.image"></image>
                    </view>
                    <view class="right dis-flex flex-box flex-dir-column flex-x-around">
                        <text class="twolist-hidden">{{ item.name }}</text>
                        <text class="">￥{{ item.goods_price }}</text>
                    </view>
                </view>

                <!-- 选择评价 -->

                <view class="score-row dis-flex flex-x-around">
                    <view
                        @tap="setScore"
                        :class="'score-item score__praise dis-flex flex-y-center flex-x-center ' + (formData[index].score == 10 ? '__active' : '')"
                        :data-index="index"
                        data-score="10"
                    >
                        <view class="score">
                            <text class="score__icon iconfont icon-haoping"></text>
                            <text class="score__text">好评</text>
                        </view>
                    </view>
                    <view
                        @tap="setScore"
                        :class="'score-item score__review dis-flex flex-y-center flex-x-center ' + (formData[index].score == 20 ? '__active' : '')"
                        :data-index="index"
                        data-score="20"
                    >
                        <view class="score">
                            <text class="score__icon iconfont icon-zhongping"></text>
                            <text class="score__text">中评</text>
                        </view>
                    </view>
                    <view
                        @tap="setScore"
                        :class="'score-item score__negative dis-flex flex-y-center flex-x-center ' + (formData[index].score == 30 ? '__active' : '')"
                        :data-index="index"
                        data-score="30"
                    >
                        <view class="score">
                            <text class="score__icon iconfont icon-chaping"></text>
                            <text class="score__text">差评</text>
                        </view>
                    </view>
                </view>

                <!-- 评价内容 -->

                <view class="dis-flex content-row">
                    <textarea @input="contentInput" :data-index="index" maxlength="2000" placeholder="请输入评价内容 (留空则不评价)" placeholderStyle="color:#ccc"></textarea>
                </view>

                <!-- 图片列表 -->

                <view class="image-list">
                    <view class="image-preview" v-for="(imagePath, imageIndex) in formData[index].image_list" :key="imageIndex">
                        <text class="image-delete iconfont icon-shanchu" @tap.stop.prevent="deleteImage" :data-index="index" :data-image-index="imageIndex"></text>

                        <image mode="aspectFill" :src="imagePath"></image>
                    </view>
                    <view
                        @tap="chooseImage"
                        class="image-picker dis-flex flex-dir-column flex-x-center flex-y-center"
                        :data-index="index"
                        v-if="!formData[index].image_list || formData[index].image_list.length < 6"
                    >
                        <text class="choose__icon iconfont icon-tubiao_xiangji"></text>
                        <text class="choose__text">上传图片</text>
                    </view>
                </view>
            </view>
        </view>

        <view class="flow-fixed-footer b-f">
            <view class="flow-btn f-32">
                <view @tap.stop.prevent="submit">确认提交</view>
            </view>
        </view>
    </view>
</template>

<script>
const app = getApp();
export default {
    data() {
        return {
            // 页面参数
            options: null,

            // 待评价商品列表
            goodsList: [],

            // 表单数据
            formData: [],

            submitDisable: false,
            score: 0,
            image_list: [],
            imageIndex: 0,
            imagePath: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        // 记录页面参数
        this.options = options;

        // 获取待评价商品列表
        this.getGoodsList();
    },
    methods: {
        /**
         * 获取待评价商品列表
         */
        getGoodsList: function () {
            let that = this;
            app.globalData._get(
                'comment/order',
                {
                    order_id: this.options.order_id
                },
                function (result) {
                    console.log(result);
                    let goodsList = result.data.goodsList;
                    that.setData({
                        goodsList,
                        formData: that.initFormData(goodsList)
                    });
                }
            );
        },

        /**
         * 初始化form数据
         */
        initFormData: function (goodsList) {
            let data = [];
            goodsList.forEach(function (item) {
                data.push({
                    item_id: item.item_id,
                    order_goods_id: item.order_goods_id,
                    score: 10,
                    content: '',
                    image_list: [
                        // 'http://tmp/wxe1997e687ecca54e.o6zAJs38WC0RISx_rydS4v4D778c.VzVJOgmUHlH3fd47776794bd803898289bebee12d94c.jpg',
                        // 'http://tmp/wxe1997e687ecca54e.o6zAJs38WC0RISx_rydS4v4D778c.u8PUZLBNG2ELa7692fe0b9dfebf762cf0cb3677a42d7.jpg',
                        // 'http://tmp/wxe1997e687ecca54e.o6zAJs38WC0RISx_rydS4v4D778c.8PjhMmysqokY55a19834d4135fbf72d4e653010d375e.jpg'
                    ],
                    uploaded: []
                });
            });
            return data;
        },

        /**
         * 设置评分
         */
        setScore: function (e) {
            let dataset = e.currentTarget.dataset;
            this.setData({
                ['formData[' + dataset.index + '].score']: dataset.score
            });
        },

        /**
         * 输入评价内容
         */
        contentInput: function (e) {
            let index = e.currentTarget.dataset.index;
            this.setData({
                ['formData[' + index + '].content']: e.detail.value
            });
        },

        /**
         * 选择图片
         */
        chooseImage: function (e) {
            let that = this;
            let index = e.currentTarget.dataset.index;
            let imageList = that.formData[index].image_list; // 选择图片
            uni.chooseImage({
                count: 6 - imageList.length,
                sizeType: ['original', 'compressed'],
                // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'],
                // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    that.setData({
                        ['formData[' + index + '].image_list']: imageList.concat(res.tempFilePaths)
                    });
                }
            });
        },

        /**
         * 删除图片
         */
        deleteImage: function (e) {
            let dataset = e.currentTarget.dataset;
            let image_list = this.formData[dataset.index].image_list;
            image_list.splice(dataset.imageIndex, 1);
            this.setData({
                ['formData[' + dataset.index + '].image_list']: image_list
            });
        },

        /**
         * 表单提交
         */
        submit: function () {
            let that = this;
            let formData = that.formData; // 判断是否重复提交
            if (that.submitDisable === true) {
                return false;
            }
            // 表单提交按钮设为禁用 (防止重复提交)
            that.submitDisable = true;
            uni.showLoading({
                title: '正在处理...',
                mask: true
            });

            // form提交执行函数
            let fromPostCall = function (formData) {
                console.log('fromPostCall');
                console.log(formData);
                app.globalData._post_form(
                    'comment/order',
                    {
                        order_id: that.options.order_id,
                        formData: JSON.stringify(formData)
                    },
                    function (result) {
                        if (result.code === 1) {
                            app.globalData.showSuccess(result.msg, function () {
                                uni.navigateBack();
                            });
                        } else {
                            app.globalData.showError(result.msg);
                        }
                    },
                    false,
                    function () {
                        uni.hideLoading();
                        that.submitDisable = false;
                    }
                );
            };

            // 统计图片数量
            let imagesLength = 0;
            formData.forEach(function (item, formIndex) {
                if (item.content !== '') {
                    imagesLength += item.image_list.length;
                }
            });

            // 判断是否需要上传图片
            if (imagesLength > 0) {
                that.uploadFile(imagesLength, formData, fromPostCall);
            } else {
                fromPostCall(formData);
            }
        },

        /**
         * 上传图片
         */
        uploadFile: function (imagesLength, formData, callBack) {
            // POST 参数
            let params = {
                //app_id: App.siteInfo.appid,
                token: uni.getStorageSync('token')
            };
            // 文件上传
            let i = 0;
            formData.forEach(function (item, formIndex) {
                if (item.content !== '') {
                    item.image_list.forEach(function (filePath, fileKey) {
                        uni.uploadFile({
                            url: app.globalData.api_root + 'upload/image',
                            filePath: filePath,
                            name: 'iFile',
                            formData: params,
                            success: function (res) {
                                let result = typeof res.data === 'object' ? res.data : JSON.parse(res.data);
                                if (result.code === 1) {
                                    item.uploaded[fileKey] = result.data.file_id;
                                }
                            },
                            complete: function () {
                                i++;
                                if (imagesLength === i) {
                                    // 所有文件上传完成
                                    console.log('upload complete');
                                    // 执行回调函数
                                    if (callBack) {
                                        callBack(formData);
                                    }
                                }
                            }
                        });
                    });
                }
            });
        }
    }
};
</script>
<style>
@import './comment.css';
</style>
